package com.example.administrator.android01app;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class Ch10Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_ch10);


    }

    public void query(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);
        SQLiteDatabase sqLiteDatabase=myDbHelper.getReadableDatabase();//打开数据库的同时，会检测数据库是否存在，如果不存在，则进行创建。
        //Cursor cursor=sqLiteDatabase.query("student",new String[]{"id","stuname"},"id=?",new String[]{"2"},null,null,null);
        Cursor cursor=sqLiteDatabase.query("student",new String[]{"id","stuname"},null,null,null,null,null);
        while (cursor.moveToNext()){//每次指向一条新记录，直至最后
            int id=cursor.getInt(cursor.getColumnIndex("id"));
            String stuname=cursor.getString(cursor.getColumnIndex("stuname"));

            Log.i(Ch10Activity.class.toString(),"id:"+id+"stuname:"+stuname);
        }
        cursor.close();
        sqLiteDatabase.close();//关闭
    }

    public void insert(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase();

        sqLiteDatabase.execSQL("insert into student(height,stuname)values(?,?)",new String[]{"180","Tom"});
        sqLiteDatabase.close();//关闭
    }

    public void delete(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase();

        sqLiteDatabase.delete("student","id=?",new String[]{"1"});

        sqLiteDatabase.close();//关闭
    }

    public void update(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase();
        ContentValues contentValues=new ContentValues();//保存需要更新的数据
        contentValues.put("stuname","Bob");

        sqLiteDatabase.update("student",contentValues,"id=?",new String[]{"2"});

        sqLiteDatabase.close();//关闭
    }


}
